﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomControlDatabaseInterface.ViewModel
{
    public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        public ViewModelBase()
        {
        }

        public virtual string DisplayName { get; protected set; }

        public void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,  
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                string msg = "Invalid property name: " + propertyName;
                throw new Exception(msg);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            this.VerifyPropertyName(propertyName);

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }


        public void Dispose()
        {
            this.OnDispose(); 
        }

        protected virtual void OnDispose()
        {
        }

        public ObservableCollection<T>ConvertToObservableCollection<T>(List<T> list)
        {
            ObservableCollection<T> result = new ObservableCollection<T>();
            foreach (T item in list)
            {
                result.Add(item);
            }
            return result;
        }

        protected void UpdateObservableCollection<T>(ObservableCollection<T> oldList, List<T> newList) {
            oldList.Clear(); 
            foreach (T item in newList) {
                oldList.Add(item);
            }
        }

    }
}
